<?php
namespace  App\Models\Forms;

use App\Emoji;
use App\Helper;
use App\Lib\Sdk\Spider\PddSpider;
use App\Models\IReadable;
use Encore\Admin\Widgets\Form;

class Template extends \stdClass
{
    protected $tags = [
        'title' => '{标题}',
        'shortTitle' =>'{短标题}',
        'couponPrice' =>'{券后价}',
        'originPrice' =>'{原价}',
        'couponDiscount' =>'{优惠券价格}',
      //  'link' =>'{商品链接}',
        'couponLink' =>'{领券链接}',
        'sales' =>'{销量}',
        'article' =>'{介绍文案}',
        'cover' =>'{商品图片}',
        'shop' =>'{店铺类型}',
        'rate' =>'{佣金比例}',
        'skuId' =>'{商品ID}',
        'couponExpire' =>'{券过期时间}',
      //  'tkl' => '{淘口令}'
    ];

    protected $callbackTags = [
        '{随机表情}' => [Emoji::class, "randomEmoji"],

    ];


    public $title;
    public $shortTitle;
    public $couponPrice; //
    public $originPrice;
    public $couponDiscount;   //优惠券价格,折扣价格
    public $link;               //商品短链接
    public $couponLink;
    public $sales;
    public $description;
    public $cover;
    public $shop;  //淘宝，天猫，京东，拼多多
    public $rate;
    public $skuId;
    public $couponExpire;
    public $tkl = "";
    public $images = [];
    public $article = "";
    public $search_id;

    public $templateString = "
  {标题}
【在售】{原价}
【群内】{券后价}
下单链接：{淘口令}";



    public function setTemplate($string)
    {
        if (!empty($string)) {
            $this->templateString = $string;
        }
    }
    /**
     * @param $data
     * @return Template
     *  {
    array (size=36)
    'category_id' => int 50024142
    'category_name' => string '显示屏/LCD液晶屏/LED屏/TFT屏' (length=36)
    'commission_rate' => string '6000' (length=4)
    'coupon_amount' => string '10' (length=2)
    'coupon_end_time' => string '2020-08-07' (length=10)
    'coupon_id' => string '88d35246b4234829ac51e497b3f54183' (length=32)
    'coupon_info' => string '满11元减10元' (length=16)
    'coupon_remain_count' => int 99951
    'coupon_start_fee' => string '11' (length=2)
    'coupon_start_time' => string '2020-06-24' (length=10)
    'coupon_total_count' => int 100000
    'item_description' => string '' (length=0)
    'item_id' => float 614383513889
    'item_url' => string 'https://item.taobao.com/item.htm?id=614383513889' (length=48)
    'level_one_category_id' => int 50024099
    'level_one_category_name' => string '电子元器件市场' (length=21)
    'nick' => string '橘辉月' (length=9)
    'num_iid' => float 614383513889
    'pict_url' => string 'https://img.alicdn.com/bao/uploaded/i4/2207676310451/O1CN01p5Cy1L1FCbDY6QC9m_!!0-item_pic.jpg' (length=93)
    'provcity' => string '广东 深圳' (length=13)
    'real_post_fee' => string '8.00' (length=4)
    'reserve_price' => string '54.63' (length=5)
    'seller_id' => float 2207676310451
    'shop_dsr' => int 50000
    'shop_title' => string 'u[2207676310451]' (length=16)
    'short_title' => string '全新15寸17 19 22 led液晶显示器灯条' (length=44)
    'small_images' =>
    array (size=2)
    0 => string 'https://img.alicdn.com/i1/2207676310451/O1CN01hjgGXC1FCbDRvqdUb_!!2207676310451.jpg' (length=83)
    1 => string 'https://img.alicdn.com/i2/2207676310451/O1CN01a9i9sj1FCbDWq7Qp8_!!2207676310451.jpg' (length=83)
    'title' => string '全新15寸17寸19寸22寸led灯条液晶显示器lcd灯管改装led背光套件' (length=80)
    'tk_total_commi' => string '0' (length=1)
    'tk_total_sales' => string '0' (length=1)
    'user_type' => int 0
    'volume' => int 0
    'white_image' => string '' (length=0)
    'zk_final_price' => string '54.47' (length=5)
    'tkl' => string '￥rqzX1D3Z2KW￥' (length=17)
    'url' => string 'https://s.click.taobao.com/r1UZ6zu' (length=34) */
    public static function getTaobaoProduct_bak($data)
    {
        $hasCoupon = !empty($data['coupon_info']) ? true: false;
        $model = new self();
        $model->title = $data['title'];
        $model->shortTitle = $data['short_title'];
        $model->couponPrice =$data['zk_final_price'];
        $model->originPrice =$hasCoupon ? $data['reserve_price'] : $data['zk_final_price'];
        $model->couponDiscount = $hasCoupon ?$data["coupon_start_fee"]: $model->originPrice  ;   //优惠券价格,折扣价格
        $model->link = $data['url'];               //商品短链接
        $model->couponLink = $data['url'];
        $model->sales  = $hasCoupon ? $data['tk_total_sales'] : 0;
        $model->description = empty($data['item_description']) ? $model->title : $data['item_description'];
        $model->cover = $data['pict_url'];
        $model->shop = $data['user_type'] == 0 ? "淘宝": "天猫";  //淘宝，天猫，京东，拼多多
        $model->rate = $data['commission_rate']/100;
        $model->skuId = $data['item_id'];
        $model->couponExpire  = $hasCoupon ? $data['coupon_end_time'] : "";
        $model->tkl = $data['tkl'];
        $model->images = $data['small_images'];
        return $model;
    }

    //dai
    public static function getTaobaoProduct($data)
    {
        $hasCoupon = true;
        $model = new self();
        $model->title = $data['itemtitle'];
        $model->shortTitle = $data['itemshorttitle'];
        $model->couponPrice =$data['couponmoney'];
        $model->originPrice =$data['itemprice'];
        $model->couponDiscount = $data["discount"]  ;   //优惠券价格,折扣价格
        $model->link = $data['planlink'];               //商品短链接
        $model->couponLink = $data['couponurl'];
        $model->sales  = $hasCoupon ? $data['itemsale'] : 0;
        $model->description = empty($data['itemdesc']) ? $model->title : $data['itemdesc'];
        $model->cover = $data['itempic'];
        $model->shop = $data['shoptype'] == 'C' ? "淘宝": "天猫";  //淘宝，天猫，京东，拼多多
        $model->rate = $data['tkrates']/100;
        $model->skuId = $data['itemid'];
        $model->couponExpire  = $hasCoupon ? $data['couponendtime'] : "";
        $model->tkl = "";
        $model->article = $data['guide_article'];  //文案
        $model->images = explode(',',$data['taobao_image']);
        return $model;
    }

    /**
     * @param array $data
     * @return Template
     * [{
    goods_id: 62273505882,
    goods_name: "大希地 八仙过海海鲜礼盒含龙虾红鱼巴沙鱼三文鱼扇贝 礼盒装（现货）",
    goods_img: "http:\/\/img14.360buyimg.com\/imgzone\/jfs\/t1\/88597\/10\/7060\/164868\/5df9c8baEb712dcfa\/681dd72036236ed7.jpg",
    goods_price: 399,
    goods_content: "京东商城,品质无忧,万里挑一!",
    goods_link: "http:\/\/item.jd.com\/62273505882.html",
    discount_price: 100,
    discount_link: "http:\/\/coupon.m.jd.com\/coupons\/show.action?key=94245d88f32d4006829e257fdf52ed88&roleId=26805424&to=mall.jd.com",
    discount_start: 1577253540000,
    discount_end: 1579103940000,
    coupon_price: 299,
    goods_type: 6,
    commission: 20,
    goods_level: 5,
    shop_type: 0,
    today_number: "391"
    }]
     */

    public static function getJdProduct(array $data)
    {
        $model = new self();
        $model->title = $data['goods_name'];
        $model->shortTitle = $model->title;
        $model->originPrice = $data['goods_price'];
        $model->couponPrice = $data['coupon_price'];
        $model->couponDiscount = $data['discount_price'];   //优惠券价格,折扣价格
        $model->couponLink = $data['discount_link'];
        $model->couponExpire = date("Y-m-d H:i:s", $data['discount_end'] / 1000);
        $model->article = $data['goods_content'];
        $model->link = $data['shortURL'];               //商品短链接
        $model->sales  = 0;
        $model->description =   $model->title;//$data['goods_content'];
        $model->cover = $data['goods_img'];
        $model->shop = "京东";  //淘宝，天猫，京东，拼多多
        $model->rate = $data['commission'];
        $model->skuId = $data['goods_id'];
        $model->images =[$model->cover];

        return $model;
    }

    private function getTemplateConfig()
    {
        $config = null;
        switch ($this->shop) {
            case "天猫":
            case "淘宝":
                $config = config("robot.templates.taobao");
                break;
            case "京东":
                $config = config("robot.templates.jd");
                break;
            case "拼多多":
                $config = config("robot.templates.pdd");
                break;
        }
        return $config;
    }

    private function getCircleConfig()
    {
        return config("robot.templates.circle");
    }

    public function getStringByTemplate($isCircle = false)
    {
        if ($isCircle) {
            $config = $this->getCircleConfig();
        } else {
            $config = $this->getTemplateConfig();
        }
        if (is_null($config)) {
            $content = $this->templateString;
        } else {
            $content = $config['content'];
        }
        foreach ($this->tags as $k => $v) {
            $content = str_replace($v, $this->$k, $content);
        }
        foreach ($this->callbackTags as $k => $v) {
            $content = call_user_func_array($v, [$k, $content]);
        }
        return $content;
    }


    public function getImages()
    {

        $config = $this->getTemplateConfig();
        if (!is_null($config)) {
            $count = $config['images_count'];
        } else  {
            $count = 2;
        }
        return array_slice($this->images, 0, $count);
    }


    /**
     * @param $data
     * @return Template
     *
     */
    public static function getPddProduct($data)
    {
        $model = new self();
        $model->title = $data['goods_name'];
        $model->shortTitle = $model->title;
        $model->originPrice = bcdiv((string)$data['min_normal_price'], "100",2);
        $model->couponDiscount = bcdiv((string)$data['coupon_discount'], "100",2);  //优惠券价格,折扣价格
        $model->couponPrice = bcsub($model->originPrice, $model->couponDiscount, 2);
        $model->link = $data['shortURL'];               //商品短链接
        $model->couponLink = "";
        $model->sales  = $data['sales_tip'];
        $model->description =  $data['goods_desc'];
        $model->cover = $data['goods_image_url'] ;
        $model->shop = "拼多多";  //淘宝，天猫，京东，拼多多
        $model->rate = $data['promotion_rate'] / 100;
        $model->skuId = $data['goods_id'];
        $model->couponExpire = date("Y-m-d H:i:s", $data['coupon_end_time'] / 1000);
        $model->images = [$data['goods_thumbnail_url']];
        $model->article = $data['goods_desc'];
        $model->search_id = $data['search_id'];
        return $model;
    }

    public function toJson()
    {
        $attrs = array_keys($this->tags);
        $res = [];
         array_push($attrs, "search_id");
        foreach ($attrs as $attr) {
            $res[$attr] = $this->$attr;
        }
        return \GuzzleHttp\json_encode($res);
    }
}

